<template>
	<view class="container">
	  <div class="topTitle">交通气象</div>
		<div class="main">
			<div class="mainSelect">
				<div class="title">
					<div class="currentCol station">
						<div class="left"></div>
						<div class="text">选择地点</div>
					</div>
					<div class="currentCol">
						<div class="left"></div>
						<div class="text">选择日期</div>
					</div>
				</div>
				<div class="center">
					<div class="item">
						<div class="currentCol station">
							<up-image src="/static/start.png" width="48rpx" height="58rpx"></up-image>
							<div class="text">
								<uni-data-picker
									:localdata="addressData"
									:clear-icon="false"
									@change="handleStartAddressChange"
								>
									<div class="selectText">{{startPoint}}</div>
								</uni-data-picker>
							</div>
						</div>
						<div class="currentCol selectDate">
							<uni-data-select
								:clear = "false"
								v-model = "text"
							  :localdata="dataList"
							  @change="selectStartChange"
								class="selectText point"
							>
							</uni-data-select>
						</div>
					</div>
					<div class="item">
						<div 	class="currentCol station">
								<up-image src="/static/end.png" width="48rpx" height="58rpx"></up-image>
								<div class="text">
									<uni-data-picker
										:localdata="addressData"
										:clear-icon="false"
										@change="handleEndAddressChange"
									>
										<div class="selectText ">{{endPoint}}</div>
									</uni-data-picker>
							</div>
						</div>		
						<div class="currentCol selectDate">
							<uni-data-select
								:clear = "false"
							  v-model="value"
							  :localdata="dataList"
							  @change="selectEndChange"
								class="selectText point"
							>
							</uni-data-select>
						</div>
					</div>
				</div>
				<div class="queryButton">
					<up-button type="primary" color='linear-gradient( 180deg, #6FA4FD 0%, #468BFA 100%)' class="custom-style" @click="queryData">查询</up-button>
				</div>
			 </div>
			 <!-- 中间预报区域 -->
			<div class="centerForecast">
				<div class="item">
					<div class="top">
						<div class="left">
							<div class="text">
								<image src="/static/position.png" mode="heightFix"></image>
								<span>{{startStation}}</span>
							</div>
							<div>{{startDate}}</div>
						</div>
						<image class="right" :src="('../../static/weather/weatherIcon_'+stianqiTu+'.png')" mode="heightFix"></image>
					</div>
					<div class="bottom">
						<div class="left">{{stmin24}}°/{{stmax24}}°</div>
						<div class="right">
							<p>{{stianqi}}</p>
							<p>{{sfengxiang}}风</p>
						</div>
					</div>
				</div>
				<div class="item">
					<div class="top">
						<div class="left">
							<div class="text">
								<image src="/static/endStation.png" mode="heightFix"></image>
								<span>{{endStation}}</span>
							</div>
							<div>{{endDate}}</div>
						</div>
						<image class="right" :src="('../../static/weather/weatherIcon_'+etianqiTu+'.png')" mode="heightFix"></image>
						</div>
						<div class="bottom">
							<div class="left">{{etmin24}}°/{{etmax24}}°</div>
							<div class="right">
								<p>{{etianqi}}</p>
								<p>{{efengxiang}}风</p>
							</div>
					</div>
				</div>
			</div>
			
			<!-- 未来七天天气预报 -->
			<div class="sevenForecast">
				<div class="title">
					<div></div>
					<p>未来七天天气预报</p>
				</div>
				
				<div class="box"  v-for="item in dataList" :key="item.date">
					<div class="left">
						<p>{{item.weekDay}}</p>
						<span>{{item.date}}</span>
					</div>
					<div class="item">
						<div class="text">
							<image src="/static/position.png" mode="heightFix"></image>
							<span>{{startStation}}</span>
						</div>
						<div class="tianqi">
							<div>
								<image :src="('../../static/weather/weatherIcon_'+item.stianqiTu1+'.png')" mode="heightFix"></image>
								<p>{{item.stianqi1}}</p>
							</div>
							<span>{{item.stmax24}}°/{{item.stmin24}}°</span>
							<div>
								<image :src="('../../static/weather/weatherIcon_'+item.stianqiTu2+'.png')" mode="heightFix"></image>
								<p>{{item.stianqi2}}</p>
							</div>
						</div>
					</div>
					<div class="item">
						<div class="text">
							<image src="/static/endStation.png" mode="heightFix"></image>
							<span>{{endStation}}</span>
						</div>
						<div class="tianqi">
							<div>
								<image :src="('../../static/weather/weatherIcon_'+item.etianqiTu1+'.png')" mode="heightFix"></image>
								<p>{{item.etianqi1}}</p>
							</div>
							<span>{{item.etmax24}}°/{{item.etmin24}}°</span>
							<div>
								<image :src="('../../static/weather/weatherIcon_'+item.etianqiTu2+'.png')" mode="heightFix"></image>
								<p>{{item.etianqi2}}</p>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</view>
</template>

<script setup>
	import { ref, reactive } from 'vue';
	import stationList from '@/static/json/station.json';
	import { onLoad } from '@dcloudio/uni-app';
	import common from '@/static/js/common.js';
	
	let currentDate = new Date(); //获取当前时间
	let year = currentDate.getFullYear();
	let month = String(currentDate.getMonth() + 1).padStart(2, '0');
	let day = String(currentDate.getDate()).padStart(2, '0');
	let currentTime = year + "-" + month + "-" + day;
	
	let startLon = ref(114.0433);  //开始站点经度，默认信阳
	let startLat = ref(32.1372);  //开始站点纬度，默认信阳
	let endLon = ref(113.6628);  //结束站点经度，默认郑州
	let endLat = ref(34.7064);  //结束站点经度，默认郑州
	let value = ref('');      //起点默认选中的日期
	let text = ref('');      //终点默认选中的日期
	let startDate = ref('');  // 开始站点选中的日期
	let endDate = ref('');  //结束站点选中的日期
	let stianqi = ref(""); //起点天气
	let etianqi = ref(""); //终点天气
	let stianqiTu = ref(""); //起点天气图
	let etianqiTu = ref(""); //终点天气图
	let stmax24 = ref(""); //起点最高温
	let etmax24 = ref(""); //终点最高温
	let stmin24 = ref(""); //起点最低温
	let etmin24 = ref(""); //终点最低温
	let sfengxiang = ref(""); //起点风向
	let efengxiang = ref(""); //终点风向
	const startPoint = ref("信阳");  //开始站名，默认信阳
	const endPoint = ref("郑州"); //结束站名，默认郑州
	const startStation = ref("信阳"); //开始站名，默认信阳
	const endStation = ref("郑州"); //结束站名，默认郑州
	const dataList = reactive([]);  //起点及终点1-7天的预报数据等
	const addressData = ref([]); //河南省所以国家站的站点，经纬度等信息

	// 处理数据转换
	const processStationData = (data) => {
	  const cityMap = new Map();
	  data.forEach(item => {
	    const cityName = item.CITY?.trim()
	    const countyName = item.STATIONNAME?.trim()
	    if (!cityName || !countyName) return
	    // 处理城市层级
	    if (!cityMap.has(cityName)) {
	      cityMap.set(cityName, {
	        text: cityName,    // 显示名称
	        value: cityName,   // 实际值
	        children: []
	      })
	    }
	    // 处理区县层级
	    const city = cityMap.get(cityName);
	    const existing = city.children.find(c => c.value === countyName);
	    if (!existing) {
	      city.children.push({
	        text: countyName,
	        value: {  // 将经纬度存入value
          name: countyName,
          lon: item.STATIONLON,
          lat: item.STATIONLAT
					}
	      })
	    }
	  })
	  return Array.from(cityMap.values())
	}
	
	// 处理起点变化时，及时更新选中站点的经纬度
	const handleStartAddressChange = (e) => {
	  const selected = e.detail.value;
	  startPoint.value = selected[1].text;
		startLon.value = selected[1].value.lon;
		startLat.value = selected[1].value.lat;
	}
	
	// 处理终点变化时，及时更新选中站点的经纬度
	const handleEndAddressChange = (e) => {
		const selected = e.detail.value;
		endPoint.value = selected[1].text;
		endLon.value = selected[1].value.lon;
		endLat.value = selected[1].value.lat;
	}
	
	// 选择起点所需日期
	const selectStartChange = (e) => {
		 startDate.value = e;
		 dataList.forEach(item => {
			 if(item.text == e) {
				 stianqi = item.stianqi1;
				 stianqiTu = item.stianqiTu1;
				 stmax24 = item.stmax24;
				 stmin24 = item.stmin24;
				 sfengxiang = item.sfengxiang;
			 }
		 })
	}
	
	// 选择终点所需日期
	const selectEndChange = (e) => {
		// console.log(startDate.value,333333)
		 endDate.value = e;
		 dataList.forEach(item => {
			 if(item.text == e) {
				 etianqi = item.etianqi1;
				 etianqiTu = item.etianqiTu1;
				 etmax24 = item.etmax24;
				 etmin24 = item.etmin24;
				 efengxiang = item.efengxiang;
			 }
		 })
	}
	
	//点击查询按钮时更新站名及对应的预报数据
	const queryData = () => {
		if (startStation.value !== startPoint.value || endStation.value !== endPoint.value) {
			initData(startLon,endLon,startLat,endLat);
		}
		startStation.value = startPoint.value;
		endStation.value = endPoint.value;
	}
	
		// 1-7天预报
		const initData = (lon1,lon2,lat1,lat2) => {
			let currentDate = new Date(); //获取当前时间
			let year = currentDate.getFullYear();
			let month = String(currentDate.getMonth() + 1).padStart(2, "0");
			let day = String(currentDate.getDate()).padStart(2, "0");
			let hours = String(currentDate.getHours() + 1).padStart(2, "0");
			let startTime = new Date(
				year + "-" + month + "-" + day + " " + "08:00:00"
			);
			let times = startTime.getTime();
			let query = {
				beginTime: common.parseTime(times), //查询起始时间
				endTime: common.parseTime(times + 604800000), //查询结束时间
				interhour: 24, //时效间隔（1、3、6、12、24）
				lon1: lon1.value,  //起点的具体经度,多个以逗号隔开
				lon2: lon2.value, //终点的具体经度,多个以逗号隔开
				lat1: lat1.value, //起点的具体纬度,多个以逗号隔开
				lat2: lat2.value //终点的具体纬度,多个以逗号隔开
			};
		 uni.request({
		 	url: `http://218.28.7.243:10003/Weather/NWP?u=APPUSE&p=0690affb28cf9b9774785ac680d44ca3&projectname=&calltype=4&iquery=Stream.GetJxhByTypeCodeAndTimeRangeAndLocation|1|String;JXH_HN|Int32;${query.interhour || 3}|DateTime;${query.beginTime}|DateTime;${query.endTime}|String;${query.lon1},${query.lon2}|String;${query.lat1},${query.lat2}&tk=${Date.now()}`,
		 	success: (res) => {
		 		let startArr = res.data[0].elementlist; //起点的预报数据
		 		let endtArr = res.data[1].elementlist; //终点的预报数据
				// console.log(startArr,111111)
				//对起点的数据进行处理
		    if(startArr.length>0) {
		      for(let i=0; i<startArr.length; i++) {
						if(i ==0) {
							dataList[0].weekDay = "今天";
							dataList[0].stianqi1 =  common.formatWeather(startArr[i].elementvalue[0], 2);
							dataList[0].stianqiTu1 =  common.formatWeather(startArr[i].elementvalue[0], 1);
							dataList[0].stianqi2 =  common.formatWeather(startArr[i].elementvalue[1], 2);
							dataList[0].stianqiTu2 =  common.formatWeather(startArr[i].elementvalue[1], 1);
							dataList[0].stmax24 = Math.round(startArr[i].elementvalue[2]);
							dataList[0].stmin24 = Math.round(startArr[i].elementvalue[3]);
							dataList[0].sfengxiang = common.getWindDirection(startArr[i].elementvalue[4],startArr[i].elementvalue[5]);
						} 
						else {
						  dataList[i].stianqi1 =  common.formatWeather(startArr[i].elementvalue[0], 2);
						  dataList[i].stianqiTu1 =  common.formatWeather(startArr[i].elementvalue[0], 1);
							dataList[i].stianqi2 =  common.formatWeather(startArr[i].elementvalue[1], 2);
						  dataList[i].stianqiTu2 =  common.formatWeather(startArr[i].elementvalue[1], 1);
						  dataList[i].stmax24 = Math.round(startArr[i].elementvalue[2]);
						  dataList[i].stmin24 = Math.round(startArr[i].elementvalue[3]);
							dataList[i].sfengxiang = common.getWindDirection(startArr[i].elementvalue[4],startArr[i].elementvalue[5]);
						}
		      }
		    };
				
				//对终点的数据进行处理
				if(endtArr.length>0) {
				  for(let i=0; i<endtArr.length; i++) {
						  dataList[i].etianqi1 =  common.formatWeather(endtArr[i].elementvalue[0], 2);
						  dataList[i].etianqiTu1 =  common.formatWeather(endtArr[i].elementvalue[0], 1);
							dataList[i].etianqi2 =  common.formatWeather(endtArr[i].elementvalue[1], 2);
						  dataList[i].etianqiTu2 =  common.formatWeather(endtArr[i].elementvalue[1], 1);
						  dataList[i].etmax24 = Math.round(endtArr[i].elementvalue[2]);
						  dataList[i].etmin24 = Math.round(endtArr[i].elementvalue[3]);
							dataList[i].efengxiang = common.getWindDirection(endtArr[i].elementvalue[4],endtArr[i].elementvalue[5]);
				  }
				};
				
				//根据当前所选日期更新中间预报区域起点所需的数据
				if (startDate.value == currentTime ){
					stianqi = dataList[0].stianqi1;
					stianqiTu = dataList[0].stianqiTu1;
					stmax24 = dataList[0].stmax24;
					stmin24 = dataList[0].stmin24;
					sfengxiang = dataList[0].sfengxiang;
				
				} 
				else {
					dataList.forEach(item => {
						 if(item.text == startDate.value) {
							 stianqi = item.stianqi1;
							 stianqiTu = item.stianqiTu1;
							 stmax24 = item.stmax24;
							 stmin24 = item.stmin24;
							 sfengxiang = item.sfengxiang;
						 }
					})
				}
				
				//根据当前所选日期更新中间预报区域终点所需的数据
				if (endDate.value == currentTime ){
					etianqi = dataList[0].etianqi1;
					etianqiTu = dataList[0].etianqiTu1;
					etmax24 = dataList[0].etmax24;
					etmin24 = dataList[0].etmin24;
					efengxiang = dataList[0].efengxiang;
				} 
				else {
					dataList.forEach(item => {
						 if(item.text == endDate.value) {
						   etianqi = item.etianqi1;
							 etianqiTu = item.etianqiTu1;
							 etmax24 = item.etmax24;
							 etmin24 = item.etmin24;
							 efengxiang = item.efengxiang;
						 }
					})
				}
				}
			})
		}
		
		// 1-7天的时间列表
		const getDateList = () => {
			value = currentTime;
			text = currentTime;
			startDate.value = currentTime;
			endDate.value = currentTime;
			for (let i = 0; i < 7; i++) {
				let newTimeDate = new Date(Date.now() + 86400000 * i); //计算出之后7天每天的时间戳，转成日期展示
				let weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
				dataList.push({
					'value': String(newTimeDate.getFullYear()) + '-' + String(newTimeDate.getMonth()+1).padStart(2, '0') + '-' + String(newTimeDate.getDate()).padStart(2, '0'),
					'text': String(newTimeDate.getFullYear()) + '-' + String(newTimeDate.getMonth()+1).padStart(2, '0') + '-' + String(newTimeDate.getDate()).padStart(2, '0'),
					'date': String(newTimeDate.getMonth()+1).padStart(2, '0') + '/' + String(newTimeDate.getDate()).padStart(2, '0'),
					'weekDay': weekDays[newTimeDate.getDay()
				]})
			}
		}
		
		// 页面加载时处理数据
		onLoad(() => {
			addressData.value = processStationData(stationList);
			getDateList();
			initData(startLon,endLon,startLat,endLat);
		})
</script>

<style lang="scss" scoped>
	* {
		scrollbar-width: none; /* 隐藏滚动条（适用于较新版本的浏览器） */
	}
	.container {
		background-image: url('/static/background.png');
		background-repeat: no-repeat;
		background-position: center;
		background-size: 100% 100%;
		overflow-y: scroll;
		.topTitle {
			padding: 0 0 54rpx 30rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 550;
			font-size: 36rpx;
			color: #181818;
			line-height: 2;
			text-align: left;
			font-style: normal;
		}
		.main {
			width: 100vw;
			.mainSelect {	
				padding: 32rpx;
				box-sizing: border-box;
				background: linear-gradient( 180deg, rgba(255,255,255,0.25) 0%, #FFFFFF 100%);
				box-shadow: 0rpx 4rpx 8rpx 4rpx rgba(127,156,255,0.55);
				border-radius: 32rpx 32rpx 0rpx 0rpx;
				border: 1rpx solid rgba(255,255,255,0.7);
				.currentCol {
					display: flex;
					align-items: center;
				}
				.station {
					width: 62%;
				}
				.title {
					width: 100%;
					display: flex;
					align-items: center;
					margin-bottom: 38rpx;
					.left {
						width: 6rpx;
						height: 28rpx;
						background: #468BFB;
						border-radius: 0rpx 4rpx 4rpx 0rpx;
					}
					.text {
						margin-left: 16rpx;
						font-family: PingFangSC, PingFang SC;
						font-weight: 550;
						font-size: 30rpx;
						color: #181818;
						line-height: 28rpx;
						text-align: left;
						font-style: normal;
					}
				}
				.center {
					.item {
						display: flex;
						justify-content: start;
						margin-bottom: 20rpx;
						.text {
							width: 80%;
						}
						.selectDate {
							padding-left: 0;
							width: 36%;
						}
						:deep(.uni-stat-box) {
							width:100%;
							background-color: rgba(255,255,255,0);
						}		
						:deep(.uni-select) {
							border: none;
							font-size: 28rpx;
						}		
						:deep(.uni-select__selector-item) {
							font-size: 26rpx;
						}
					}
					.selectText {
						width: 100%;
						height: 80rpx;
						line-height: 80rpx;
						font-weight: 550;
						padding-left: 20rpx;
						font-size: 28rpx;
						color: #03050D;
						background-color: rgba(255,255,255,0);
						border: none;
						border-bottom: 1rpx solid #DFE1E9;
					}
					.point {
						padding-left: 0;
					}
				}
				.queryButton {
					.custom-style {
						height: 100rpx;
						font-size: 30rpx;
						border-radius: 16rpx;
					}
				}
			}
			.centerForecast {
				padding:  48rpx 32rpx;
				background-color: rgba(255,255,255,0.8);
				display: flex;
				align-items: center;
				justify-content: space-between;
				.item {
					width: 48%;
					background: linear-gradient( 180deg, rgba(124,191,253,0.22) 0%, rgba(173,204,255,0.08) 100%);
					box-shadow: 0rpx 4rpx 32rpx 0rpx rgba(70,139,251,0.11);
					border: 2rpx solid #FFFFFF;
					border-radius: 32rpx;
					padding: 0 16rpx 16rpx 16rpx; 
					box-sizing: border-box;
					.top {
						height: 116rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						.left{
							width: 60%;
							.text {
								height: 60rpx;
								display: flex;
								align-items: center;
								image {
									height: 32rpx;
								}
								span {
									margin-left: 4rpx;
									font-weight: 400;
									font-size: 28rpx;
									color: #333333;
									line-height: 40rpx;
								}
							}
							div {
								font-weight: 400;
								font-size: 22rpx;
								color: #999999;
								line-height: 32rpx;
								text-align: left;
							}
						}
						.right {
							height: 100rpx;
						}
					}
					.bottom {
						width: 100%;
						height: 75rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						.left {
							width: 55%;
							text-align: center;
							font-family: DINAlternate, DINAlternate;
							font-weight: bold;
							font-size: 45rpx;
							color: rgba(77,139,252,0.8);
							text-shadow: 0rpx 4rpx 12rpx rgba(25,91,200,0.17);
						}
						.right {
							p {
								font-weight: 400;
								font-size: 24rpx;
								color: #333333;
								line-height: 34rpx;
								text-align: right;
							}
						}
					}
				}
			}
			.sevenForecast {
				padding: 32rpx;
				background: #FFFFFF;
				box-shadow: 0px 4px 18px 4px rgba(127,156,255,0.15);
				.title {
					display: flex;
					margin-bottom: 24rpx;
					div {
						width: 6rpx;
						height: 28rpx;
						background: #468BFB;
						border-radius: 0rpx 4rpx 4rpx 0rpx;
					}
					p {
						margin-left: 16rpx;
						font-weight: 550;
						font-size: 30rpx;
						color: #181818;
						line-height: 28rpx;
					}
				}
				.box {
					width: 100%;
					height: 160rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-weight: 400;
					text-align: center;
					border-radius: 12rpx;
					border: 2rpx solid rgba(70,139,251,0.08);
					margin-bottom: 20rpx;
					box-sizing: border-box;
					.left {
						width: 20%;
						height: 160rpx;
						border-right: 2rpx solid rgba(70,139,251,0.13);
						// background: rgba(127,156,255,0.5);
						font-size: 28rpx;
						color: #181818;
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: center;
						span {
							font-size: 24rpx;
							color: #999999;
							line-height: 50rpx;
						}
					}
					.item {
						width: 40%;
						// background: rgba(127,156,255,0.5);
						.point {
							border-right: 2rpx solid rgba(70,139,251,0.13);
						}
						.text {
							height: 60rpx;
							display: flex;
							justify-content: center;
							align-items: center;
							border-bottom: 2rpx solid rgba(70,139,251,0.13);
							image {
								height: 24rpx;
							}
							span {
								margin-left: 6rpx;
								font-size: 24rpx;
								color: #666666;
								line-height: 50rpx;									
							}
						}
						.tianqi {
							height: 100rpx;
							display: flex;
							justify-content: space-around;
							align-items: center;
							div{
								image {
									height: 40rpx;
								}
								p {
								font-size: 24rpx;
								color: #333333;
								line-height: 34rpx;
								}
							}
							span {
								font-weight: 550;
								font-size: 32rpx;
								color: #181818;
								line-height: 44rpx;
							}
						}
					}
				}
				.box > :nth-child(2) {
					border-right: 2rpx solid rgba(70,139,251,0.13);
				}
			}
			.sevenForecast > :nth-child(2) {
				background: linear-gradient( 180deg, #FFFFFF 0%, #F6F9FF 100%);
				box-shadow: 0rpx 0rpx 12rpx 0rpx rgba(70,139,251,0.15);
			}
		}
	}
</style>
